package cn.mymall.web.controller;

import cn.mymall.constant.MallConstant;
import cn.mymall.entity.Member;
import cn.mymall.entity.mall.CartItem;
import cn.mymall.entity.mall.Product;
import cn.mymall.entity.mall.Sku;
import cn.mymall.service.mall.ICartItemService;
import cn.mymall.service.mall.IProductService;
import cn.mymall.service.mall.ISkuService;
import cn.mymall.service.mall.ISubCategoryService;
import cn.mymall.support.ResultCode;
import cn.mymall.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.support.PropertyComparator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@Controller
public class CartItemController extends BaseController{
    @Autowired
    private IProductService productService;
    @Autowired
    private ISkuService skuService;
    @Autowired
    private ICartItemService cartItemService;
    @Autowired
    private ISubCategoryService subCategoryService;

    @RequestMapping("/home/cart")
    public String cart(ModelMap model) {
        List<CartItem> list = cartItemService.findByMemberId(getLoginMember().getId());
        Collections.sort(list, new PropertyComparator<>("addTime", false, false));
        List<Map> resMapList = new ArrayList();
        for (CartItem item : list) {
            Sku sku = skuService.getById(item.getSkuId());
            Product product = productService.getById(sku.getProductId());
            Map map = new HashMap();
            map.put("cartItemId", item.getId());
            map.put("productId", item.getProductId());
            map.put("vendorId", product.getVendorId());
            map.put("categoryId", product.getCategoryId());
            map.put("qty", item.getQty());
            map.put("sellPrice", item.getSellPrice());
            map.put("skuId", item.getSkuId());
            map.put("productName", product.getName());
            map.put("skuName", sku.getName());
            map.put("logo", product.getLogo());
            map.put("booking", sku.hasBooking() && product.hasBooking());
            resMapList.add(map);
        }
        model.put("cartList", resMapList);
        return "front/home/cart.ftl";
    }


    @RequestMapping(value = "/home/cartItem/add")
    @ResponseBody
    public ResultCode addCartItem(Integer skuId, Integer qty) {
        Member member = getLoginMember();
        if(member == null){
            return ResultCode.getFailure("未获取到用户信息");
        }
        if (skuId == null || qty == null) {
            return ResultCode.getFailure("缺少参数");
        }

        if (qty <= 0) {
            return ResultCode.getFailure("数量异常");
        }
        Sku sku = skuService.getById(skuId);
        if (sku == null) {
            return ResultCode.getFailure("sku不存在");
        }
        if (!sku.hasStock()) {
            return ResultCode.getFailure("库存不足，请选择其他商品！");
        }
        if (sku.gainStock() < qty) {
            return ResultCode.getFailure("超过商品库存，请编辑数量！");
        }
        Product product = productService.getById(sku.getProductId());
        if(product ==null || !product.hasBooking()){
            return ResultCode.getFailure("商品已下架，不能购买");
        }
        if(StringUtils.isNotBlank(product.getPartnerGoodsId())){
            return ResultCode.getFailure("该商品不能加入购物车，只能单独购买");
        }
        Integer memberId = member.getId();
        CartItem cartItem = cartItemService.findByMemberIdAndSkuId(memberId, skuId);

        if(cartItem == null){
            cartItem = new CartItem(memberId, sku, qty);
            cartItem.setAddTime(DateUtil.getCurFullTimestamp());
        }
        //检查购物车商品总数量，是否超过最大限制
        List<CartItem> itemList = cartItemService.findByMemberId(memberId);
        int tmp = 0;
        for (CartItem item : itemList) {
            tmp = tmp + item.getQty();
        }

        tmp += qty;
        if (tmp >= MallConstant.CART_ITEM_MAX) {
            return ResultCode.getFailure("购物车最多只能添加数量：" + MallConstant.CART_ITEM_MAX);
        }

        cartItem.setQty(qty);
        cartItemService.saveOrUpdate(cartItem);
        int count = cartItemService.findCountByMemberId(memberId);
        return ResultCode.getSuccessReturn(count);
    }

    @RequestMapping(value = "/home/cartItem/del")
    @ResponseBody
    public ResultCode delCartItem(Integer cartItemId) {
        Member member = getLoginMember();
        if(member == null){
            return ResultCode.getFailure("未获取到用户信息");
        }
        if (cartItemId == null) {
            return ResultCode.getFailure("缺少参数");
        }
        CartItem cartItem = cartItemService.getById(cartItemId);
        if (cartItem == null) {
            return ResultCode.getFailure("购物车不存在！");
        }
        if (!member.getId().equals(cartItem.getMemberId())) {
            return ResultCode.getFailure("无权操作！");
        }
        cartItemService.removeById(cartItem);
        return ResultCode.getSuccessReturn(cartItemService.findCountByMemberId(member.getId()));
    }
    @RequestMapping(value = "/home/cartItem/count")
    @ResponseBody
    public ResultCode<Integer> cartItemCount() {
        Member member = getLoginMember();
        if(member == null){
            return ResultCode.getSuccessReturn(0);
        }
        return ResultCode.getSuccessReturn(cartItemService.findCountByMemberId(member.getId()));
    }
}
